﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Communergy.EnergyMonitor;
using System.Configuration;
using System.Runtime.Remoting.Metadata.W3cXsd2001;
using System.Threading;
using Communergy.Common;
using Communergy.Common.Factories;
using Communergy.Common.Events;

namespace Communergy.EnergyMonitorProviders
{
    public class EnergyMonitorProvider_Basic : IEnergyMonitorProvider
    {
        TimeSpan readingsInterval;
        Thread readingThread;

        int baseWatts = 0;
        int currentWatts = 0;


        #region IEnergyMonitorProvider Members

        public event NewReadingHandler EnergyReading;

        public EnergyMonitorProvider_Basic()
        {
            string readingsIntervalConfig = ConfigurationSettings.AppSettings["ReadingsInterval"];
            readingsInterval = SoapDuration.Parse(readingsIntervalConfig);


            string wattsConfig = ConfigurationSettings.AppSettings["Watts"];
            int wattsConverted;
            if (int.TryParse(wattsConfig, out wattsConverted))
            {
                baseWatts = wattsConverted;
            }
        }


        private void RunReadings()
        {   
            while (true)
            {
                var readingDateTime = DateTime.Now.ToUniversalTime();
                Thread.Sleep((int)readingsInterval.TotalMilliseconds);

                //TODO - monitor machine?
                currentWatts = baseWatts;

                int thisWatts = currentWatts;
                int joules = (int)readingsInterval.TotalSeconds * thisWatts;
                var newReading = new RealtimeEnergyReading
                {
                    Joules = joules,
                    ReadingDateTime = readingDateTime,
                    Watts = thisWatts
                };
                var newEnergyReadingEventArgs = new EnergyReadingEventArgs
                {
                    RealtimeEnergyReading = newReading
                };
                RaiseNewReadingEvent(newEnergyReadingEventArgs);                
            }            
        }


        private void RaiseNewReadingEvent(EnergyReadingEventArgs re)
        {
            if (EnergyReading != null)
            {
                EnergyReading(this, re);
            }
        }



        public void StartReadings()
        {
            readingThread = new Thread(RunReadings);
            readingThread.Start();
        }

        public void EndReadings()
        {
            readingThread.Abort();
        }

        #endregion
    }
}
